﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Raven.Client;
using TimeTracker.Entities;
using TimeTracker.Persistence.Indexes;

namespace TimeTracker.Persistence
{
    public static class SearchExtensions
    {
        /// <summary>
        /// Searches by a single token
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="keyword">A single keyword that is going to be used as a token.</param>
        /// <returns>The entries matching the results.</returns>
        public static IEnumerable<Entry> FindByRelevanceTokenized(this IDocumentSession session, string keyword)
        {
            return from entry in session.Query<Entry, EntriesFullTextSearchIndex>()
                   where entry.Description.StartsWith(keyword)
                   select entry;
        }

        /// <summary>
        /// Searches using a collection of tokens.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="keywords">The keyworks in string form that will be separated by whitespace.</param>
        /// <returns>The entries matching the results</returns>        
        public static IEnumerable<Entry> FindByRelevance(this IDocumentSession session, string keywords)
        {
            var query = (IQueryable<Entry>)session.Query<Entry, EntriesFullTextSearchIndex>();
            return keywords.Split().Aggregate(query, (current, part) => current.Where(x => x.Description.StartsWith(part)));
        }

        /// <summary>
        /// Searches using a collection of tokens.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="keywords">The list of keywords to use in exact form</param>
        /// <returns>The entries matching the results</returns>
        public static IEnumerable<Entry> FindByRelevanceTokenized(this IDocumentSession session, IEnumerable<string> keywords)
        {
            var query = (IQueryable<Entry>) session.Query<Entry, EntriesFullTextSearchIndex>();
            return keywords.Aggregate(query, (current, part) => current.Where(x => x.Description.StartsWith(part)));
        }

    }
}
